import React, { Component } from 'react'
import { connect } from 'dva';
import api from '@/api';
import get from 'lodash/get';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Card, Row, Col, Form, Select, Button, message, Divider } from 'antd'

import StandardTable from '@/components/StandardTable';
import ScrollSelect from '@/components/ScrollSelect';

import styles from './Create.less'

const FormItem = Form.Item
const { Option } = Select
@connect(({ base, loading, product }) => ({
  serviceTypes: base.serviceTypes,
  loading: loading.effects['productService/queryServices'],
  product: product.products
}))
@Form.create()
class CreateProductService extends Component {
  state = {
    selectedRows: [],
    serviceList: {
      list: [],
      pagination: {}
    }
  }
  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
      width: 80,
    },
    {
      title: '服务名称',
      dataIndex: 'name',
    },
    {
      title: '服务类型',
      dataIndex: 'serviceTypeName',
    },
    {
      title: '供应商',
      dataIndex: 'supplierName',
    },
    {
      title: '服务编码',
      dataIndex: 'code',
    },
  ]
  calcIndex = index => {
    const { serviceList } = this.props;
    let currentPage = get(serviceList, 'pagination.currentPage') || 1;
    let pageSize = get(serviceList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };
  componentDidMount() {
    this.queryServiceType()
    this.queryProducts()
  }
  queryServices = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form } = this.props;
    form.validateFields(['serviceTypeCode', 'airport'], (err, value) => {
      if (err) return
      dispatch({
        type: 'productService/queryServices',
        payload: {
          queryParams: {
            pageIndex,
            pageSize,
            ...rest,
            serviceTypeCode: value.serviceTypeCode,
            airport: value.airport.key
          }
        }
      }).then(({ errorCode, data, pagination }) => {
        if (errorCode === 0) {
          this.setState({ serviceList: { list: data, pagination } })
        }
      })
    })

  }
  queryServiceType = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'base/fetchServiceTypes'
    })
  }
  queryProducts = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/fetch'
    })
  };
  queryAirports = params => {
    return api.base.queryAirport({
      queryParams: params,
    });
  };
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleBind = () => {
    const { selectedRows } = this.state;
    const { form, dispatch, serviceTypes } = this.props;
    const product = form.getFieldValue('product')
    if (!product || product.length === 0) {
      message.error('请选择产品')
      return
    }
    if (selectedRows.length === 0) {
      message.error('请选择服务')
      return
    }

    form.validateFields((err, value) => {
      if (err) return
      dispatch({
        type: 'productService/createProductService',
        payload: {
          data: {
            productIdList: value.product,
            serviceIdList: selectedRows.map(item => item.id),
            serviceTypeCode: value.serviceTypeCode,
            serviceTypeName: serviceTypes.filter(item => item.code === value.serviceTypeCode)[0].name
          }
        }
      }).then(({ errorCode, data }) => {
        if (errorCode === 0) {
          message.success('添加成功')
          form.resetFields()
          this.setState({ selectedRows: [], serviceList: { list: [], pagination: {} } })
        }
      })
    })
  }
  resetConditions = () => {
    const { form: { resetFields } } = this.props;
    resetFields()
    this.setState({ serviceList: { list: [], pagination: {} } })
  }
  render() {
    const { form: { getFieldDecorator }, loading, serviceTypes, product } = this.props;
    const { serviceList, selectedRows } = this.state;
    return (
      <PageHeaderWrapper title='返回' backRoute='/product/bind'>
        <Card bordered={false}>
          <div className={styles.search}>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col span={8}>
                <FormItem label="产品" required>
                  {getFieldDecorator('product')(
                    <Select
                      mode='multiple'
                      allowClear
                      style={{ width: '100%' }}
                    >
                      {
                        product.list.filter(item => item.id === '10000' || item.id === '10001').map(item => (
                          <Option key={item.id}>{item.name}</Option>
                        ))
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Divider />
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="服务类型">
                  {getFieldDecorator('serviceTypeCode', {
                    rules: [
                      {
                        required: true, message: '请选择服务类型'
                      }
                    ]
                  })(
                    <Select style={{ width: '100%' }} allowClear>
                      {
                        serviceTypes.filter(item => item.code !== 'ST003').map(item => (<Option value={item.code} key={item.code}>{item.name}</Option>))
                      }
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="服务机场">
                  {getFieldDecorator('airport', {
                    rules: [
                      {
                        required: true, message: '请选择服务类型'
                      }
                    ]
                  })(
                    <ScrollSelect
                      allowClear
                      search={this.queryAirports}
                      optionKey="code"
                      style={{ width: '100%' }}
                    />
                  )}
                </FormItem>
              </Col>
              <Col md={8} sm={24}>
                <Button onClick={this.resetConditions}>重置</Button>
                <Button type="primary" onClick={() => this.queryServices()}>
                  查询
              </Button>
              </Col>
            </Row>
          </div>
          <div className={styles.operate}>
            <Button type="primary" onClick={this.handleBind}>
              保存
              </Button>
          </div>
          <StandardTable
            rowKey="id"
            loading={loading}
            showCheckbox
            selectedRows={selectedRows}
            data={serviceList}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    )
  }
}

export default CreateProductService
